<template>
  <div>
    <!--添加按钮 -->
    <el-button type="primary" icon="el-icon-plus" @click="addOrsetInfo"
      >添加</el-button
    >

    <!-- 内容表单 -->
    <el-table border :data="trademarkList" style="width: 100%; margin: 20px 0">
      <!-- 序号列 -->
      <el-table-column label="序号" type="index" align="center" width="80">
      </el-table-column>
      <!-- 品牌名称列 -->
      <el-table-column
        prop="tmName"
        label="品牌名称"
        width="width"
        align="center"
      >
      </el-table-column>
      <!-- 品牌LOGO列 -->
      <el-table-column
        prop="prop"
        label="品牌LOGO"
        width="width"
        align="center"
      >
        <!-- 插槽 插入 img标签 -->
        <template v-slot="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 80px; height: 60px" />
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column prop="prop" label="操作" width="width" align="center">
        <template v-slot="{ row, $index }">
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-edit"
            @click="addOrsetInfo(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="remove(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 页码 -->
    <el-pagination
      style="text-align: center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :pager-count="5"
      :page-sizes="[3, 5, 7]"
      :page-size="limit"
      layout=" prev, pager, next ,jumper,->,sizes,total"
      :total="total"
    >
    </el-pagination>

    <!-- 添加弹窗 -->
    <el-dialog
      :title="form.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <!-- 输入框 -->
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="form.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 添加图片 -->
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendNewInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  mounted() {
    this.handleCurrentChange();
  },
  data() {
    return {
      page: 1, //当前页
      limit: 3, //每页条数
      trademarkList: [],
      total: 0, //总数量
      dialogFormVisible: false,
      form: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "最少2位最多10位字符",
            trigger: "change",
          },
        ],
        logoUrl: [{ required: true, message: "请LOGO图片" }],
      },
    };
  },
  methods: {
    /* 初始化请求数据 */
    async handleCurrentChange(page = 1) {
      this.page = page;
      try {
        const re = await this.$api.trademark.GetPagesInfo(
          this.page,
          this.limit
        );
        if (re.code === 20000 || re.code === 200) {
          this.trademarkList = re.data.records;
          this.total = re.data.total;
          /* console.log(this.trademarkList); */
        } else {
          this.$message.error("获取品牌列表失败");
        }
      } catch (error) {
        this.$message.error("请求品牌列表失败");
      }
    },

    /* 修改每页的数据条数 */
    handleSizeChange(val) {
      this.limit = val;
      this.handleCurrentChange();
    },

    /* 点击新增和修改弹出窗口并更新数据 */
    addOrsetInfo(row) {
      this.dialogFormVisible = true;
      if (row.id) {
        /*  console.log("修改") */
        this.form = {
          ...row,
        };
      } else {
        /* console.log("新增") */
        this.form = {
          tmName: "",
          logoUrl: "",
        };
      }
    },

    /* 发送修改或新增的数据 */
    sendNewInfo() {
      /* 发送前的表单验证 */
      this.$refs.form.validate( async (valid) => {
        if (!valid) {
          this.$message.error("请确保输入正确的品牌名和LOGO");
          return;
        } else {
          this.dialogFormVisible = false;

          /* 获取需要发送的数据 */
          let sendInfo = this.form;
          /* console.log(sendInfo) */
          /* 发送请求  请求函数api以判断新增还是修改 */
          try {
            const re = await this.$api.trademark.addOrUpdata(sendInfo);
            if (re.code === 20000 || re.code === 200) {
              this.$message.success("操作成功");
              /* 修改或增加成功后  如果新增则跳到第一页，如果修改则保持当前页，重新最新渲染数据 */
              this.handleCurrentChange(sendInfo.id ? this.page : 1);
            } else {
              this.$message.error("修改或新增品牌列表失败");
            }
          } catch (error) {
            this.$message.error("发送修改或新增品牌列表失败");
          }
        }
      });
    },

    /* 删除数据 发送删除数据id */
    remove(row) {
      this.$confirm(`此操作将删除${row.tmName},是否继续`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            let id = row.id;
            const re = await this.$api.trademark.remove(id);
            if (re.code === 20000 || re.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.handleCurrentChange(
                this.trademarkList.length > 1 ? this.page : this.page - 1
              );
            } else {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
            }
          } catch (error) {
            this.$message({
              type: "error",
              message: "请求删除失败!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    /* 添加图片请求 */
    /* 上传图片 图片处理 */
    handleAvatarSuccess(res, file) {
      this.form.logoUrl = res.data;
    },
    /* 审核图片格式和图片大小 */
    beforeAvatarUpload(file) {
      const isJPGorPng =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPng) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPGorPng && isLt2M;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>